import React, { memo } from "react"
import { useAppSelector } from "@/store"
import { shallowEqual } from "react-redux"
import { useNavigate } from "react-router-dom"
import * as Icons from "@ant-design/icons"
import "./index.less"
interface Iprops {
	title: string
	url: string
	closeable?: boolean
	icon: string
	closeItem: Function
}
const NavItem: React.FC<Iprops> = (props) => {
	const { title, url, icon, closeable = false, closeItem } = props
	// 动态渲染 Icon 图标
	const customIcons: { [key: string]: any } = Icons
	const addIcon = (name: string) => {
		return React.createElement(customIcons[name])
	}
	const navigate = useNavigate()
	const { primary, current } = useAppSelector(
		(state) => ({
			primary: state.layoutStore.primary,
			current: state.menusStore.current,
		}),
		shallowEqual,
	)
	const jump = (e: any) => {
		e.stopPropagation()
		if (["SPAN", "path", "DIV", "svg"].includes(e.target.nodeName)) {
			console.log(e.target.nodeName)
			navigate(url)
		}
	}
	const colse = (e: any) => {
		e.stopPropagation()
		if (e.target.nodeName === "I") {
			closeItem({ title, url, icon, closeable })
		}
	}
	return (
		<div
			className={`nav-item ${current.url === url ? "active" : ""}`}
			style={{ backgroundColor: primary }}
			onClick={jump}
		>
			{icon && addIcon(icon)}
			<span className="title" style={{ marginLeft: icon ? "5px" : "" }}>
				{title}
			</span>
			{closeable && (
				<i className="close" onClick={colse}>
					x
				</i>
			)}
		</div>
	)
}

export default memo(NavItem)
